//
//  OAuthViewController.swift
//  TYHWeibo
//
//  Created by IOS on 15/7/31.
//  Copyright © 2015年 IOS. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController,UIWebViewDelegate {

    //MARK:搭建界面
    private lazy var webView = UIWebView()
    
    override func loadView() {
        view = webView
        webView.delegate = self
        
        title = "新浪微博"
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    
    //关闭界面
    func close() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        //加载页面
        webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedTools.oauthUrl()))
        
//        view.backgroundColor = UIColor.whiteColor()
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //把URL变成字符串
        let urlString = request.URL!.absoluteString
        //判断是否包含回调地址
        if !urlString.hasPrefix(NetworkTools.sharedTools.redirectUri) {
            return true
        }
        
        print("判断参数")
        print(request.URL?.query)
        if let query = request.URL?.query where query.hasPrefix("code=") {
           let code = (query as NSString).substringWithRange(NSMakeRange(5, query.characters.count - 5))
            print(code)
            //TODO: 换取token
            loadAccessToken(code)
            
        }else {
            close()
        }
        
        
        return true
    }
    
    private func loadAccessToken(code: NSString) {
        NetworkTools.sharedTools.loadAccessToken(code) { (result, error) -> () in
            if error != nil || result == nil {
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                let when = dispatch_time(DISPATCH_TIME_NOW, Int64(2 * NSEC_PER_SEC))
                dispatch_after(when, dispatch_get_main_queue(), { () -> Void in
                    self.close()
                })
                
                return
            }
//            print(result)
            let account = UserAccount(dict: result!)
            account.loadUserInfo({ (error) -> () in
                if error != nil {
                    self.netError()
                    return
                }
//                print("ok")
                //发送通知切换控制器
                NSNotificationCenter.defaultCenter().postNotificationName(TYHRootViewControllerSwitchNotification, object: false)
            })
            
//            account.saveAccount()
//            NetworkTools.sharedTools.loadUserInfo(account.uid!, finished: { (result, error) -> () in
//                print(result)
//            })
//            print(account)
            
            
            
            
        }
    
    }
 
    private func netError() {
        SVProgressHUD.showInfoWithStatus("您的网络不给力")
        let when = dispatch_time(DISPATCH_TIME_NOW, Int64(2 * NSEC_PER_SEC))
        dispatch_after(when, dispatch_get_main_queue(), { () -> Void in
            self.close()
        })
    
    }

}
